package com.pzh.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pzh.usercenter.model.domain.User;
import com.pzh.usercenter.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务
 */
@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private List<Long> mainUsers = Arrays.asList(1L);

    //每天凌晨四点插入缓存
    @Scheduled(cron = "0 0 4 * * ? ")
    public void doCacheCommendUsers() {
        RLock lock = redissonClient.getLock("yupao:precachejob:docache:lock");
        try {
            //每天所有线程尝试一次获取锁，等待0s，拿到执行，否则放弃
            // -1 ，看门狗机制，每10s续期一次
            if (lock.tryLock(0,-1, TimeUnit.SECONDS)) {
                System.out.println("lock" + Thread.currentThread().getId());
                for (Long mainUserId : mainUsers) {
                    //key
                    String userKey = String.format("yupao:user:recommend:%s", mainUserId);
                    //查数据库
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    //存入redis,设置过期时间 15s
                    try {
                        valueOperations.set(userKey,userPage,60, TimeUnit.SECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error",e);
                    }
                }
            }

        } catch (InterruptedException e) {
            log.error("redis lock error",e);
        } finally {
            //只能释放自己的锁
            if(lock.isHeldByCurrentThread()){
                System.out.println("unlock" + Thread.currentThread().getId());
                lock.unlock();
            }
        }

    }

}
